//
//  IGLiveViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGLiveViewController.h"
#import "IGLiveListTableViewCell.h"
#import "IGLiveList2TableViewCell.h"
#import "IGLiveListHeaderView.h"
#import "IGLiveListModel.h"
#import "IGLivePlayer.h"

@interface IGLiveViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, assign) NSInteger requestIndex;

@property (nonatomic, strong) IGLivePlayer *livePlayer;

@property (nonatomic, strong) UIButton *backButton;

@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;
@end

@implementation IGLiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor grayColor];
    
    // 注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"IGLiveListTableViewCell" bundle:nil] forCellReuseIdentifier:@"LiveListCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IGLiveList2TableViewCell" bundle:nil] forCellReuseIdentifier:@"LiveListCell2"];
  
//    // 表头
//    IGLiveListHeaderView *header = [[IGLiveListHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
//    _tableView.tableHeaderView = header;
    
    // 初始化数组
    _dataArr = [NSMutableArray array];
    
    // 请求数据
    [self requestData];
    
    // MJ刷新
    _requestIndex = 0;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _requestIndex = 0;
        [self requestData];
        
    }];
    
    // 通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(closeNotification) name:@"closeUserInteractionEnabled" object:nil];
    [center addObserver:self selector:@selector(openNotification) name:@"openUserInteractionEnabled" object:nil];


}

// 手势冲突
- (void)closeNotification
{
    _tableView.userInteractionEnabled = NO;
}

- (void)openNotification
{
    _tableView.userInteractionEnabled  = YES;
}


#pragma mark -- 网络请求
- (void)requestData
{
    
      [IGAFNetworking requestWithUrlString:@"http://api.maxjia.com:80/api/live/list/?phone_num=00000000000&pkey=randpkey&os_type=iOS&os_version=9.1&_time=1452496590&version=3.0.0&limit=30&offset=0" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
          
          NSArray *resultArr = dataDic[@"result"];
          [_dataArr removeAllObjects];
          for (NSDictionary *oneDic in resultArr) {
              
              IGLiveListModel *model = [[IGLiveListModel alloc] init];
              [model setValuesForKeysWithDictionary:oneDic];
              [_dataArr addObject:model];
              
          }
          
          [self.tableView.mj_header endRefreshing];
          [_tableView reloadData];
          
      } error:^(NSError *requestError) {
          NSLog(@"%@",requestError);
      }];
    
    
}


#pragma mark -- data source

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
    
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        
        IGLiveList2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LiveListCell2"];
        IGLiveListModel *model = _dataArr[indexPath.row];
        cell.model = model;
        return cell;
        
    }else{
    
        IGLiveListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LiveListCell"];
        IGLiveListModel *model = _dataArr[indexPath.row];
        cell.model = model;
        return cell;
    }
}

// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return 180;
    }else{
        return 100;
    }
    
}

// cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    IGLiveListModel *model = _dataArr[indexPath.row];
    [self videoPlayWithlive_type:model.live_type live_id:model.live_id live_title:model.live_title];
    
}


- (void)videoPlayWithlive_type:(NSString *)live_type live_id:(NSString *)live_id live_title:(NSString *)live_title
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"live_type"] = live_type;
    parDic[@"live_id"] = live_id;
    parDic[@"phone_num"] = @"00000000000";
    parDic[@"pkey"] = @"randpkey";
    parDic[@"os_type"] = @"iOS";
    parDic[@"os_version"] = @"8.2";
    parDic[@"_time"] = @"1452518952";
    parDic[@"version"] = @"3.0.0";
    parDic[@"device_id"] = @"E62A9982-2FE5-423D-BD3C-5E2FEC8F5681";
    
    
    [IGAFNetworking requestWithUrlString:@"http://api.maxjia.com:80/api/live/detail/?" parDic:parDic metho:POST finish:^(NSDictionary *dataDic) {
        
        NSDictionary *resultDic = dataDic[@"result"];
        NSArray *streamlistArr= resultDic[@"stream_list"];
        NSString *url = streamlistArr[0][@"url"];
        
        // 创建播放器
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        _livePlayer = [[IGLivePlayer alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) URL:[NSURL URLWithString:url]];
        [appDelegate.window addSubview:_livePlayer];
    
        // 观察播放器状态(开始播放时指示器停止动画)
        [_livePlayer addObserver:self forKeyPath:@"vlcPlayer.state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        
        // 播放器view上的子视图
        [self addLivePlayer];
        
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
}

// 添加播放界面子视图
- (void)addLivePlayer
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _backButton.frame = CGRectMake(kScreenWidth - 35, 20, 25, 25);
    [_backButton setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [appDelegate.window addSubview:_backButton];

    
    [self allScreen];
    
    _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    _activityIndicatorView.frame = CGRectMake((kScreenWidth - 25) / 2, (kScreenHeight - 25) / 2, 25, 25);
    [appDelegate.window addSubview:_activityIndicatorView];
    [_activityIndicatorView startAnimating];
}

// 跳出播放界面
- (void)backButtonClick:(UIButton *)button
{
    // 不管值有没有变 都要
    [_livePlayer removeObserver:self forKeyPath:@"vlcPlayer.state" context:nil];

    [_livePlayer.vlcPlayer stop];
    [_livePlayer removeFromSuperview];
    [_backButton removeFromSuperview];
    [_activityIndicatorView removeFromSuperview];
    

}

// 进入播放界面后全屏
- (void)allScreen
{
        
    [UIView animateWithDuration:0.1 animations:^{
        
        _livePlayer.frame = CGRectMake(0, 0, kScreenHeight, kScreenWidth);
        _livePlayer.center = CGPointMake(kScreenWidth / 2, kScreenHeight / 2);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.1 animations:^{
            
            _livePlayer.transform = CGAffineTransformRotate(_livePlayer.transform, M_PI_2);
            _backButton.transform = CGAffineTransformRotate(_backButton.transform, M_PI_2);
            
        }];
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    NSInteger state = [change[@"new"] integerValue];
    if (state == VLCMediaPlayerStatePlaying) {
        [_activityIndicatorView stopAnimating];
    }
    
    
    
}

- (BOOL)shouldAutorotate
{
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
